package com.niodata.dp.task.dao.handler;

import com.niodata.dp.mybatis.DpMybatisTypeHandler;
import com.niodata.dp.task.entity.PackageOutParams;
import com.niodata.dp.util.JsonUtil;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class PackageOutParamsTypeHandler extends BaseTypeHandler<PackageOutParams>
    implements DpMybatisTypeHandler {

  @Override
  public JdbcType getJdbcType() {
    return JdbcType.LONGVARCHAR;
  }

  @Override
  public Class<PackageOutParamsTypeHandler> getTypeHandlerClass() {
    return PackageOutParamsTypeHandler.class;
  }

  @Override
  public Class<PackageOutParams> getJavaClass() {
    return PackageOutParams.class;
  }

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, PackageOutParams parameter,
      JdbcType jdbcType) throws SQLException {
    try {
      ps.setString(i, parameter == null ? null : JsonUtil.toJson(parameter));
    } catch (IOException e) {
      throw new SQLException(e);
    }
  }

  @Override
  public PackageOutParams getNullableResult(ResultSet rs, String columnName) throws SQLException {
    try {
      String json = rs.getString(columnName);
      return json != null ? JsonUtil.fromJson(PackageOutParams.class, json) : null;
    } catch (IOException e) {
      throw new SQLException(e);
    }
  }

  @Override
  public PackageOutParams getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    try {
      String json = rs.getString(columnIndex);
      return json != null ? JsonUtil.fromJson(PackageOutParams.class, json) : null;
    } catch (IOException e) {
      throw new SQLException(e);
    }
  }

  @Override
  public PackageOutParams getNullableResult(CallableStatement cs, int columnIndex)
      throws SQLException {
    try {
      String json = cs.getString(columnIndex);
      return json != null ? JsonUtil.fromJson(PackageOutParams.class, json) : null;
    } catch (IOException e) {
      throw new SQLException(e);
    }
  }
}
